package de.dopichaj.labrador.search.own;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.dopichaj.labrador.index.Index;
import de.dopichaj.labrador.index.backend.Term;
import de.dopichaj.labrador.index.backend.TermFrequency;
import de.dopichaj.labrador.search.hit.Hit;


/**
 * A similarity function inspired by GPX.
 * It is not quite the same: It does not use collection frequency (not available
 * in our index), and it does no score propagation.
 */
public final class GPXSimilarityFactory implements SimilarityFactory {

    private final int K = 5;
    
    public GPXSimilarityFactory(final Index index) {
    }
    
    public Similarity getSimilarity(OwnQuery query) {
        return new GPXSimilarity(query);
    }

    private final class GPXSimilarity implements Similarity {

        private final Map<Integer, Integer> termWeights;

        public GPXSimilarity(final OwnQuery query) {
            termWeights = new HashMap<Integer, Integer>();
            for (final Term term : query.getQueryTerms()) {
                
                termWeights.put(term.getID(), term.getCollectionFrequency());
            }
        }

        public double similarity(Hit hit, List<TermFrequency> frequencyList) {
            
            double sum = 0;
            for (final TermFrequency tf : frequencyList) {
                sum += (double)tf.getFrequency() / termWeights.get(tf.getTermID());
            }

            final double boost = Math.pow(K, frequencyList.size() - 1);
            
            return boost * sum;
        }
    }

    public String getDescription() {
        return "GPX similarity (K=" + K + ")";
    }
}
/*
Copyright (c) 2005-2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/